/*
 * Created by JFormDesigner on Sun Aug 22 00:10:48 CST 2021
 */

package com.minelx.statementplus.ui.form.ui;

import com.minelx.landisk.filesystem.Paths;
import com.minelx.landisk.filesystem.core.File;
import com.minelx.landisk.filesystem.core.init.OpenPolicy;
import com.minelx.statementplus.ui.form.swing.DialogInputs;
import com.minelx.statementplus.ui.form.swing.OnClosingDialog;
import com.minelx.statementplus.ui.form.service.tablemapping.TableMappingFactory;
import com.minelx.statementsplus.Majors;
import com.minelx.statementsplus.cha.base.HttpChaSession;
import com.minelx.table.core.Table;
import com.minelx.table.core.Tables;
import com.minelx.table.core.series.Series;
import com.minelx.woods.task.core.SqlTaskService;
import com.minelx.woods.task.core.ChaSessionFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author aaa
 */
public class TableDialog extends OnClosingDialog {
	private final Table table;

	private final TableMappingFactory tableMappingFactory;

	private final DownloadService downloadService;

	public static void main(String[] args) {
		new TableDialog(null,
				Tables.csv("a,b,c\n1,2,3"),
				new DownloadService(new SqlTaskService(ChaSessionFactory.http()), new DefaultListModel<>())).setVisible(true);
	}

	public TableDialog(Window owner, Table table, DownloadService downloadService) {
		super(owner, e -> {
		});
		this.table = table;
		this.downloadService = downloadService;
		tableMappingFactory = TableMappingFactory.configuredMappings();
		initComponents();

		tableTextArea.setText(table.form().title().toText());
	}

	private void saveButtonActionPerformed(ActionEvent e) {
		File downloadedFile = Paths.projectRoot()
				.child().dir("downloaded_files", OpenPolicy.useExistingOrCreateANewOne())
				.child().file(DialogInputs.candyOrJoke("另存文件名称: "), OpenPolicy.createANewOne());
		try {
			downloadedFile.write(table.toText(), StandardCharsets.UTF_8);
		} catch (IOException exception) {
			exception.printStackTrace();
		}
	}

	private void simpleConversionButtonActionPerformed(ActionEvent e) {
		// choose converted column
		String[] title = table.form().title().stream().toArray(String[]::new);
		String convertedTitle = DialogInputs.chooseOneOf(this, title, "选择转换的列");

		Series<String> column = table.column(convertedTitle);

		String[] mappings = tableMappingFactory.mappingNames().toArray(new String[0]);
		String mappingKey = DialogInputs.chooseOneOf(this, mappings, "选择列类型");

		if (mappingKey.equals("t_a_member.member_id")) {
			downloadService.buildAndDownload(this, Majors.memberIds(column.stream().mapToLong(Long::parseLong).toArray()));
		} else {
			throw new RuntimeException("something is wrong here: " + mappingKey);
		}
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		panel2 = new JPanel();
		scrollPane1 = new JScrollPane();
		tableTextArea = new JTextArea();
		panel1 = new JPanel();
		saveButton = new JButton();
		simpleConversionButton = new JButton();
		label1 = new JLabel();

		//======== this ========
		setTitle("\u9884\u89c8");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		var contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== panel2 ========
		{
			panel2.setBorder(new EmptyBorder(12, 12, 12, 12));
			panel2.setLayout(new BorderLayout(0, 12));

			//======== scrollPane1 ========
			{

				//---- tableTextArea ----
				tableTextArea.setFont(new Font("Microsoft JhengHei UI Light", Font.PLAIN, 26));
				tableTextArea.setEditable(false);
				scrollPane1.setViewportView(tableTextArea);
			}
			panel2.add(scrollPane1, BorderLayout.CENTER);

			//======== panel1 ========
			{
				panel1.setLayout(new FlowLayout(FlowLayout.TRAILING));

				//---- saveButton ----
				saveButton.setText("\u4fdd\u5b58\u5f53\u524d\u6587\u4ef6");
				saveButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 22));
				saveButton.addActionListener(e -> saveButtonActionPerformed(e));
				panel1.add(saveButton);

				//---- simpleConversionButton ----
				simpleConversionButton.setText("\u5217\u8f6c\u6362");
				simpleConversionButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 22));
				simpleConversionButton.addActionListener(e -> simpleConversionButtonActionPerformed(e));
				panel1.add(simpleConversionButton);
			}
			panel2.add(panel1, BorderLayout.SOUTH);

			//---- label1 ----
			label1.setText("\u5f53\u524d\u8868\u683c\u5185\u5bb9: ");
			label1.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
			panel2.add(label1, BorderLayout.NORTH);
		}
		contentPane.add(panel2, BorderLayout.CENTER);
		setSize(715, 560);
		setLocationRelativeTo(getOwner());
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	private JPanel panel2;
	private JScrollPane scrollPane1;
	private JTextArea tableTextArea;
	private JPanel panel1;
	private JButton saveButton;
	private JButton simpleConversionButton;
	private JLabel label1;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
}
